import { connect } from 'umi';
import { ContractManageAPI } from '../common/type';
import { Form, Spin, message } from 'antd';
import { ConractControllerContext, IContractsActionEnum, useContractsReducer } from '../common';
import {
  addContractService,
  editContractService,
  getMcontractByIDService,
  editRecordContractService,
  submitRecordContractService,
  addAndSubmitContractService,
} from '../services';
import { useEffect, useState } from 'react';
import { handMainContractData } from '../mconfig';
import { ContractChangeTabsView } from './ContractChangeTabsView';
import { history } from 'umi';
import { getKeyRouter } from '@/utils';
import { readReadShowFileService } from '@/services/BaseLayout';

const ContractChangeView: React.FC<ContractManageAPI.IContractUpdate> = ({ curRes, locationProps }) => {
  /** 表单 */
  const [contractForm] = Form.useForm();

  /** 原合同表单 */
  const [oldContractForm] = Form.useForm();

  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';

  /** 获取reducets */
  const { counterpartRows, contractTempRow, contractDispatch, contarctJsonList, partyFirstSelectRows } = useContractsReducer();

  /** 保存原合同信息 */
  const [saveMainContractInfo, setSaveMainContractInfo] = useState<Record<string, any>>({});

  /** 合同详情 */
  const [contractDetailInfo, setContractDetailInfo] = useState<Record<string, any>>({});

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      const detailInfo: Record<string, any> = handMainContractData(res?.obj);
      setContractDetailInfo({});

      setContractDetailInfo(detailInfo);

      if (res?.obj && res?.obj?.oppositeList?.length > 0) {
        contractDispatch({
          type: IContractsActionEnum.SELECT_COUNTERPARTROWS,
          payload: res?.obj?.oppositeList,
        });
      }
      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {},
      });

      // 处理合同主体信息
      contractDispatch({
        type: IContractsActionEnum.SELECT_PARTYALIST,
        payload: [
          {
            oppositeName: res?.obj?.oppositeName,
            oppositeID: res?.obj?.id,
            // phoneMobile: res?.obj?.contactMobile,
            // contactName: res?.obj?.contactName,
            creditID: res?.obj?.creditID,
            bankName: res?.obj?.bankName,
            bankAccount: res?.obj?.bankAccount,
            registerPhone: res?.obj?.registerPhone,
            workAddress: res?.obj?.workAddress,
            partyId: `party-first-${getKeyRouter()}`,
          },
        ],
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDLoading, getMcontractByIDRun, reloadDetailInfo } = getMcontractByIDService(detailsCallback);

  /** 编辑回调 */
  const modifyCallback = (res: any, clickType: boolean, isNeedSubmit?: boolean) => {
    if (res && res?.msgFlag) {
      if (clickType && !isNeedSubmit) {
        const payload: Record<string, any> = {
          pIDDetailInfo: saveMainContractInfo,
          pageType: res?.obj?.changeWay == 0 ? 'modify' : res?.obj?.changeWay == 1 ? 'break' : null,
          id: res?.obj?.pID ? res?.obj?.id : null,
          pID: res?.obj?.pID,
        };

        let pageRouterUrl: string = '';
        if (payload?.pageType == 'modify') {
          pageRouterUrl = '/contractController/modifyRouter';
        } else if (payload?.pageType == 'break') {
          pageRouterUrl = '/contractController/breakRouter';
        }
        history.push({
          pathname: `${pageRouterUrl}/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            ...payload,
            delRouterName: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      } else {
        message.success(res?.msg);
        if (res?.obj?.id) {
          getMcontractByIDRun({
            id: res?.obj?.id,
          });
        } else {
          reloadDetailInfo();
        }
      }
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入接口 */
  const { editContractLoading, editContractRun } = editContractService(modifyCallback);

  const { addAndSubmitContractLoading, addAndSubmitContractRun } = addAndSubmitContractService(modifyCallback, locationProps?.state?.updateType);

  /** 添加接口 */
  const { addContractLoading, addContractRun } = addContractService(modifyCallback, locationProps?.state?.updateType);

  /** 补录编辑接口 */
  const { editRecordContractLoading, editRecordContractRun } = editRecordContractService(modifyCallback);

  /** 补录提交接口 */
  const { submitRecordContractLoading, submitRecordContractRun } = submitRecordContractService(modifyCallback);

  /** 初始化，编辑调用详情接口 */
  useEffect(() => {
    if (locationProps?.state?.id) {
      getMcontractByIDRun({
        id: locationProps?.state?.id,
      });
    }
  }, [locationProps?.state?.id]);

  /** 处理主合同数据 */
  useEffect(() => {
    if (locationProps?.state?.pIDDetailInfo?.id) {
      const mainDetail: Record<string, any> = handMainContractData(locationProps?.state?.pIDDetailInfo);
      setSaveMainContractInfo({
        ...mainDetail,
        changeFlag: 1,
        changeWay: locationProps?.state?.pageType == 'modify' ? 0 : locationProps?.state?.pageType == 'break' ? 1 : null,
      });
      // 处理合同主体信息
      contractDispatch({
        type: IContractsActionEnum.SELECT_PARTYALIST,
        payload: [
          {
            oppositeName: mainDetail?.oppositeName,
            oppositeID: mainDetail?.id,
            creditID: mainDetail?.creditID,
            bankName: mainDetail?.bankName,
            bankAccount: mainDetail?.bankAccount,
            registerPhone: mainDetail?.registerPhone,
            workAddress: mainDetail?.workAddress,
            partyId: `party-first-${getKeyRouter()}`,
          },
        ],
      });
    }
  }, [locationProps?.state?.pIDDetailInfo]);

  /** 轻阅读预览 */
  const { readReadShowFileRun, readReadShowFileLoading } = readReadShowFileService();

  return (
    <ConractControllerContext.Provider
      value={{
        styleFixCls,
        curRes,
        locationID: locationProps?.state?.id,
        contractDispatch,
        pageType: locationProps?.state?.pageType,
        counterpartRows,
        contractTempRow,
        contractForm,
        oldContractForm,
        contractDetailInfo: {
          ...contractDetailInfo,
        },
        oldContractInfo: {
          ...saveMainContractInfo,
        },
        contarctJsonList,
        reloadDetail: reloadDetailInfo,
        updteAddOrEdit: {
          addContractRun,
          editContractRun,
          editRecordContractRun,
          submitRecordContractRun,
          addAndSubmitContractRun,
        },
        locationState: locationProps?.state,
        getDetailInfoRun: () => {},
        materialCheckRows: [],
        partyFirstSelectRows,
        readReadShowFileRun,
      }}
    >
      <Spin
        spinning={
          getMcontractByIDLoading ||
          editContractLoading ||
          addContractLoading ||
          readReadShowFileLoading ||
          editRecordContractLoading ||
          submitRecordContractLoading ||
          addAndSubmitContractLoading
        }
      >
        <div
          style={{
            height: '100%',
            width: '100%',
            position: 'relative',
            overflow: 'hidden',
          }}
        >
          <ContractChangeTabsView />
        </div>
      </Spin>
    </ConractControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(ContractChangeView);
